<?php


class TcpClient
{
    private $socket;
    private $host;
    private $port;

    /**
     * 构造函数 - 初始化TCP客户端
     * @param string $host 服务器地址
     * @param int $port 服务器端口
     */
    public function __construct(string $host = '127.0.0.1', int $port = 9601)
    {
        $this->host = $host;
        $this->port = $port;
    }

    /**
     * 连接到TCP服务器
     * @return bool 连接是否成功
     * @throws Exception
     */
    public function connect(): bool
    {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($this->socket === false) {
            throw new Exception("socket_create() failed: " . socket_strerror(socket_last_error()));
        }

        $result = socket_connect($this->socket, $this->host, $this->port);
        if ($result === false) {
            throw new Exception("socket_connect() failed: " . socket_strerror(socket_last_error($this->socket)));
        }

        return true;
    }

    /**
     * 发送数据
     * @param string $data 要发送的数据
     * @return int|bool 发送的字节数或失败时返回false
     */
    public function send(string $data)
    {
//        $length = strlen($data);
//        $lengthByte = chr($length);
        $message = $data;
        echo "send data to server: $message\n";
        return socket_write($this->socket, $message, strlen($message));
    }


    /**
     * @param string $length //binary
     * @return false|int
     */
    public function send2(string $length, $message)
    {
        echo "send data to server: $length: $message\n";
        return socket_write($this->socket, $length, strlen($length));
    }

    /**
     * 接收数据
     * @param int $length 要接收的数据长度
     * @return string 接收到的数据
     */
    public function receive(int $length = 1024): string
    {
        return socket_read($this->socket, $length);
    }

    /**
     * 关闭连接
     */
    public function close()
    {
        if ($this->socket) {
            socket_close($this->socket);
        }
    }
}

/**
 * @param int $params
 * @return string
 */
function intToBin(int $params): string
{
    return decbin($params);
}


function binaryToStr($binary): string
{
    // 二进制转字符串
    $text = '';
    for ($i = 0; $i < strlen($binary); $i += 8) {
        $byte = substr($binary, $i, 8);
        $text .= chr(bindec($byte));
    }
    echo "二进制转字符串: " . $text . "\n";
    return $text;
}

/**
 * 字符串转二进制
 * @param $str
 * @return string
 */
function stringToBinary($str): string
{
    $binary = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $binary .= str_pad(decbin(ord($str[$i])), 8, '0', STR_PAD_LEFT);
    }
    return $binary;
}

/**
 * @throws Exception
 */
function get($url, $param = array(), $timeOut = 10, $protocol = "http", $debug = false)
{
    //参数是一个数组
    if (!is_array($param)) {
        throw new \Exception("参数必须为array");
    }
    //组装get提交数据
    if (!empty($param)) {
        $p = '';
        foreach ($param as $key => $value) {
            $p = $p . $key . '=' . $value . '&';
        }
        //是否拼装? / &
        if (preg_match('/\?[\d\D]+/', $url)) {//matched ?c
            $p = '&' . $p;
        } else {
            $p = '?' . $p;
        }
        //替换多余的连接符
        $p = preg_replace('/&$/', '', $p);
        $url = $url . $p;
    }
    //开始请求
    $httph = curl_init($url);
    curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($httph, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    curl_setopt($httph, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($httph, CURLOPT_HEADER, 0);
    curl_setopt($httph, CURLOPT_TIMEOUT, $timeOut);
    curl_setopt($httph, CURLOPT_CONNECTTIMEOUT, 2);//2秒链接不上，就断开
    // disable 100-continue
    curl_setopt($httph, CURLOPT_HTTPHEADER, array('Expect:'));
    //https请求
    if ("https" == $protocol) {
        curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, false);
    } elseif (is_array($protocol) && $protocol["type"] == "cookie") {
        curl_setopt($httph, CURLOPT_COOKIE, $protocol["params"]);
    }
    $result = curl_exec($httph);
    if (empty($result) && $debug) {
        echo 'result->' . $result . "->" . print_r(curl_getinfo($httph), true) . print_r(curl_error($httph), true) . PHP_EOL;
    }
    curl_close($httph);
    return $result;
}


function PHP2Erlang($type, $data = array(), $jsonData = "")
{
    if (!is_array($data)) {
        throw  new Exception("data type must be array");
    };


    $url = "https://127.0.0.1";
    $port = 19601;
    //如果$jsonData参数为空，则默认为操作
    if (empty($jsonData)) {
        $jsonData = empty($data) ? "{}" : "{" . implode(",", $data) . "}";
    }
    //请求参数
    $nowTime = time();
    $PLAT_SERVER_ID = 1;
    $PLATFORM = "release";
    $paramArr = array("platform" => $PLATFORM, "server_num" => $PLAT_SERVER_ID, "do" => $type, "data" => $jsonData, "time" => $nowTime);
    //增加token参数
    $paramArr["token"] = strtolower(md5(join("", $paramArr) . 't4EmNT0b*Hr5k$I^c8UxQoF3'));
    //使用http - get提交数据
    try {
        $response = get($url . ":" . $port . "/background", $paramArr, 20, "http", true);
        if (empty($response)) {
            return array("code" => 1, "data" => "请求异常,response empty");
        }
        $resArr = json_decode($response, true);
        echo "请求url" . $url . ":" . $port . "/background" . "请求参数" . json_encode($paramArr, true) . "返回结果:" . $response . PHP_EOL;
        if ($resArr["code"] !== 0) {
            echo print_r($resArr, true) . "\n" . $url . ":" . $port . "/background?" . urldecode(http_build_query($paramArr)) . PHP_EOL;
        }
        return $resArr;
    } catch (\Exception $e) {
        echo "请求异常\n" . $url . ":" . $port . "/background?" . urldecode(http_build_query($paramArr)) . PHP_EOL;
        return array("code" => 1, "data" => "请求异常");
    }

}


$querydata =[550];


$mail_data = [
    "mail_kind" => 1,
    "id" => 0,
    'type' => 1,
    'send_time' => time(),
    "expire_time" => time() + 86400 * 30,
    'to_rid' => 6000002921,
    "title" => "邮件",
    "content" => "邮件1111",
    "assets" => '[]',
    "item" => '[{61,1},{62,1}]'
];

$postdata = [
    "RoleType" => 1,#  						1-玩家名字  2-玩家id  用来说明  IdOrName 字段
    "IdOrName" => "test",# / 10001,				账号id或者忘记名字
    "Platform" => "dev",#						平台
    "ZoneId" => 12, #							节点id
    "Sn" => "sfasdfdfaxzca11111",        #			加密唯一充值编号
    "Amount" => 6, #							充值金额
    "CurrencyType" => "CNY", #					货币类型 CNY	货币类型
    "Category" => 1, #  						充值类型 1：普通充值、2：自充值、3：测试充值
    "package_id" => 1,     #				充值表(charge_data表)中的id
    "charge_type" => 0,#可选				充值类型
    "package_name" => "weixinh5",#可选		包名
    "pay_channel" => "wx",#可选			充值渠道
];


// $querydata = [1000000185];
// $res = PHP2Erlang(6, $mail_data);
$res = PHP2Erlang(32, $querydata);
// $dat = $res["data"];
// $aa = binaryToString($dat);
echo "return res" . json_encode($res, true) . PHP_EOL;


// 使用示例
//try {
//    // 创建TCP客户端实例
//
//    $client = new TcpClient('192.168.100.251', 9631);
//
//    // 连接服务器
//    $client->connect();
//
////    $msg1 = intToBin(12);
////    echo $msg1 . PHP_EOL;
////    $msg2 = stringToBinary("web_");
//
//    $msg1 = intToBin(12);
//    echo $msg1 . PHP_EOL;
//    $msg2 = 'web_';
//    $a1 = 'asdf';  // binary
//    $now_time = time();
//    $server_ticket = 'ticket';
////    $mdsstr = md5('123 1733383681ticket');
//    $sign = md5(sprintf("%s%d%s", $a1, $now_time, $server_ticket));
//
//    $data = [$a1, time(), $sign, ['i', 'i'], 'role_adm', 'get_role_list', [1, 10]];
//
//
//
//    $client->send("web_");
//    // 发送数据
//    $length = intToBin(strlen($data));
//    echo "length: $length" . PHP_EOL;
//   $result1 =  $client->send2($length,$data);
//   echo 'R1'.$result1 .PHP_EOL;
//
//    $result = $client->send(json_encode($data));
//    if ($result !== false) {
//        echo "Successfully sent data\n";
//
//        // 接收响应
//        $response = $client->receive(4096);
//        echo "Received response: " . $response . "\n";
//    } else {
//        throw new Exception("Failed to connect to server!");
//    }
//
//    // 关闭连接
//    $client->close();
//
//} catch (Exception $e) {
//    echo "Error: " . $e->getMessage() . "\n";
//}




function binaryToString($binary) {
    $text = '';
    for ($i = 0; $i < strlen($binary); $i += 8) {
        $byte = substr($binary, $i, 8);
        $text .= chr(bindec($byte));
    }
    return $text;
}